package cn.dyp.com.getsensordata.request;

import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import cn.dyp.com.getsensordata.bean.SensorValue;

/**
 * 获取传感器当前值的请求类
 * 
 * @author asus
 *
 */
public class GetSensorRequest extends AgricultureRequest {
	// action name
	private static final String ACTION = "getSensor";
	private SensorValue mSensorValue;

	/**
	 * 获取传感器当前值存储对象
	 * 
	 * @return SensorValue
	 */
	public SensorValue getSensorValue() {
		return mSensorValue;
	}

	/**
	 * 设置传感器当前值存储对象
	 * 
	 * @param sensorValue
	 *            setSensorValue
	 */
	public void setSensorValue(SensorValue sensorValue) {
		this.mSensorValue = sensorValue;
	}

	/**
	 * 构造函数
	 * 
	 * @param userName
	 *            用户名
	 */
	public GetSensorRequest(String userName) {
		super(userName);
	}

	/**
	 * 获取Action的Name
	 * 
	 * @see cn.dyp.com.getsensordata.request.BaseRequest#getActionName()
	 */
	@Override
	protected String getActionName() {
		return ACTION;
	}

	/**
	 * JSON封装
	 * 
	 * @see cn.dyp.com.getsensordata.request.BaseRequest#onGetJasonBody()
	 */
	@Override
	protected String onGetJasonBody() {
		JSONObject jsonObj = new JSONObject();
		try {
			jsonObj.put("username", userName);
			return jsonObj.toString();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * JSON解析
	 * 
	 * @see cn.dyp.com.getsensordata.request.AgricultureRequest#onJasonParese(String)
	 */
	@Override
	protected void onJasonParese(String responseStr) {
		try {
			JSONObject jsonRespObj = new JSONObject(responseStr);
			if (jsonRespObj != null && mSensorValue != null) {
				if (jsonRespObj.has("result")) {
					String result = jsonRespObj.getString("result");
					// 判断请求是否成功
					if (result.equalsIgnoreCase("ok")) {
						isSuccess = true;
					} else {
						isSuccess = false;
					}
				}
				// 空气湿度
				mSensorValue.setUpdataTime(new Date());
				if (jsonRespObj.has("airHumidity")) {
					mSensorValue.setAirHumid(jsonRespObj.getInt("airHumidity"));
				}
				// 空气温度
				if (jsonRespObj.has("airTemperature")) {
					mSensorValue.setAirTemper(jsonRespObj
							.getInt("airTemperature"));
				}
				// 土壤温度
				if (jsonRespObj.has("soilTemperature")) {
					mSensorValue.setSoilTemper(jsonRespObj
							.getInt("soilTemperature"));
				}
				// CO2浓度
				if (jsonRespObj.has("co2")) {
					mSensorValue.setCo2(jsonRespObj.getInt("co2"));
				}
				// 土壤湿度
				if (jsonRespObj.has("soilHumidity")) {
					mSensorValue.setSoilHumid(jsonRespObj
							.getInt("soilHumidity"));
				}
				// 灯光强度
				if (jsonRespObj.has("light")) {
					mSensorValue.setLight(jsonRespObj.getInt("light"));
				}
			} else {
				isSuccess = false;
			}
		} catch (JSONException e) {
			isSuccess = false;
			e.printStackTrace();
		}
	}
}
